<?php

class Events extends \Phalcon\Mvc\Model
{

    /**
     *
     * @var integer
     */
    public $id;

    /**
     *
     * @var integer
     */
    public $creator_id;

    /**
     *
     * @var string
     */
    public $when;

    /**
     *
     * @var string
     */
    public $venue;

    /**
     *
     * @var string
     */
    public $title;

    /**
     *
     * @var string
     */
    public $content;

    /**
     *
     * @var string
     */
    public $date_created;

    /**
     *
     * @var integer
     */
    public $group_id;

    public $long;

    public $lat;

    public $city;

    /**
     * Independent Column Mapping.
     */
    public function columnMap()
    {
        return array(
            'id' => 'id', 
            'creator_id' => 'creator_id', 
            'when' => 'when', 
            'venue' => 'venue', 
            'title' => 'title', 
            'content' => 'content', 
            'date_created' => 'date_created', 
            'group_id' => 'group_id',
            'long'=>'long',
            'lat'=>'lat',
            'city'=>'city'
        );
    }

    public function listIncomingEvents($group_id)
    {
        $phql = "SELECT e.id,e.creator_id,uat.fname,uat.lname,e.when,e.venue,e.title,e.content,e.date_created,e.group_id 
                FROM Events e 
                LEFT JOIN UserAccountTb uat ON uat.id = e.creator_id
                WHERE group_id = ?0 AND e.when > NOW()";
        $data = $this->modelsManager->executeQuery($phql,array(0=>$group_id));
        return @$data;
    }

    public function listPastEvents($group_id)
    {
        $phql = "SELECT e.id,e.creator_id,uat.fname,uat.lname,e.when,e.venue,e.title,e.content,e.date_created,e.group_id 
                FROM Events e 
                LEFT JOIN UserAccountTb uat ON uat.id = e.creator_id
                WHERE group_id = ?0 AND e.when < NOW()";
        $data = $this->modelsManager->executeQuery($phql,array(0=>$group_id));
        return @$data;
    }
    public function countIncomingEvents($group_id)
    {
        $phql = "SELECT COUNT(e.id) as total 
                FROM Events e 
                WHERE group_id = ?0 AND e.when > NOW()";
        $data = $this->modelsManager->executeQuery($phql,array(0=>$group_id));
        return @$data[0]->total;   
    }

    public function countPastEvents($group_id)
    {
        $phql = "SELECT COUNT(e.id) as total 
                FROM Events e 
                WHERE group_id = ?0 AND e.when < NOW()";
        $data = $this->modelsManager->executeQuery($phql,array(0=>$group_id));
        return @$data[0]->total;   
    }

    public function beforeValidationOnCreate()
    {
        $this->date_created = CURR_DATE;
    }


}
